import {
  createImage,
  downloadImage,
  getImageGenerationLocation,
  GetImageGenerationLocationResult,
  upLoadImage,
} from '@/api/comfyUI';
import { downloadGigaResource, getAccessToken, getProductBaseInfo } from '@/api/giga';
import { solveGigaCaptcha } from '@/api/locale';
import { generateProductTitle } from '@/api/postme';
import { getTemuUserInfo, pageQuery } from '@/api/temu';
import {
  CorssRequestMessage,
  GeneratorProductTitleMessage,
  GetGiga2bProductInfoMessage,
  GetGigaAccessTokenMessage,
  GetGigaProductPriceMessage,
  GetGigaResourceMessage,
  GetProxyMessage,
  GetTemuPageQueryMessage,
  GetTemuUserInfoMessage,
  MessageType,
  SetProxyMessage,
  SolveGigaCaptchaMessage,
} from '@/config';
import { getAcwScV2, getProductPrice, updateGigaAcwScV2CookieExtension } from '@/lib/giga';
import { getCurrentTab, getDataUrl } from '@/lib/utils';
const gigaResourceKey = 'gigaResource';
export const gigaResourceStorage = storage.defineItem<string>(`local:${gigaResourceKey}`);

export type CreateMessage = {
  type: 'create';
  link: string;
};
export default defineBackground({
  type: 'module',
  main() {
    console.log(browser, import.meta.env);

    browser.runtime.onInstalled.addListener(async () => {
      // 增加一个菜单
      browser.contextMenus.create({
        id: 'giga-resource-info',
        title: '采集详情',
        contexts: ['page'],
        documentUrlPatterns: ['https://www.gigab2b.com/*'],
      });
    });

    async function getGigaResource(gigaProductId: string) {
      try {
        const blob: Blob = await downloadGigaResource(gigaProductId);
        console.log('blob', blob);
        if (blob.type !== 'application/octet-stream') {
          if (blob.type === 'text/html') {
            const html = await blob.text();
            const match = html.match(/arg1\s*=\s*'([^']+)'/);
            // 如果返回的是 arg1 页面进行增加 cookie 处理
            if (match && match[1]) {
              const arg1 = match[1];
              console.log(arg1);
              const acwScV2 = getAcwScV2(arg1);
              console.log('acwScV2', acwScV2);
              // 更新 cookie
              await updateGigaAcwScV2CookieExtension(acwScV2);
              return getGigaResource(gigaProductId);
            } else {
              return {
                code: 3,
                msg: `受到封控策略限制导致无法获取到资源包,策略类型为验证码`,
              };
            }
          } else if (blob.type === 'application/json') {
            return {
              code: 4,
              msg: `请先登录到 gigab2b 网站`,
            };
          } else {
            return {
              code: 2,
              msg: `受到封控策略限制导致无法获取到资源包`,
            };
          }
        }
        const dataUrl = await getDataUrl(blob);
        await gigaResourceStorage.setValue(dataUrl);
        return {
          code: 0,
          msg: '获取资源包成功',
          data: gigaResourceKey,
        };
      } catch (error) {
        // if (error instanceof Error && error.message.match(/Network\s*Error/i)) {
        //   // 先进行权限更新
        //   // 如果抛出了错误,那么会终止后续的操作,否则继续进行资源获取操作
        //   console.log('出现了资源包权限获取错误', error);
        //   try {
        //     await refreshGigaResourcePermission({
        //       gigaProductId,
        //     });
        //     return getGigaResource(gigaProductId);
        //   } catch (error) {
        //     return {
        //       code: 5,
        //       msg: `${(error as Error).message}`,
        //     };
        //   }
        // } else {
        //   return {
        //     code: 1,
        //     msg: `${(error as Error).message}`,
        //   };
        // }
        return {
          code: 1,
          msg: `${(error as Error).message}`,
        };
      }
    }

    browser.runtime.onMessage.addListener(
      async (
        message:
          | GetGiga2bProductInfoMessage
          | GetGigaProductPriceMessage
          | GeneratorProductTitleMessage
          | GetGigaAccessTokenMessage
          | GetGigaResourceMessage
          | SetProxyMessage
          | GetProxyMessage
          | GetTemuUserInfoMessage
          | GetTemuPageQueryMessage
          | SolveGigaCaptchaMessage
          | CorssRequestMessage,
      ) => {
        // 用来获取 giga 中产品的详细信息
        if (message.type === MessageType.getGiga2bProductInfo) {
          const baseInfo = await getProductBaseInfo(message.data.productId);
          console.log('getGiga2bProductInfo', baseInfo);
          if (baseInfo.code === 200) {
            const product_info = baseInfo?.data?.product_info;
            if (product_info && (product_info.description || product_info.characteristic)) {
              return {
                code: 0,
                msg: '获取产品描述成功',
                data: {
                  description: product_info.description,
                  feature: product_info.characteristic,
                  productName: product_info.product_name,
                },
              };
            } else {
              return {
                code: 2,
                msg: '获取产品描述失败,需要先登录 gigab2b 网站',
              };
            }
          } else {
            return {
              code: 1,
              msg: `获取产品描述失败: 需要先登录 gigab2b 网站 ${baseInfo.code}: ${baseInfo.msg} `,
            };
          }
          // 使用 api 来获取
          // try {
          //   const gigaProductInfo = await getGigaProductInfo({
          //     sku: message.data.sku,
          //     accessToken: message.data.accessToken,
          //     tokenType: message.data.tokenType,
          //   });
          //   return {
          //     code: 0,
          //     msg: '获取 giga 产品信息成功',
          //     data: gigaProductInfo,
          //   };
          // } catch (error) {
          //   return {
          //     code: 1,
          //     msg: `获取 giga 产品信息失败: 失败原因 ${(error as Error).message} `,
          //   };
          // }
        }

        if (message.type === MessageType.getGigaProductPrice) {
          try {
            // console.log(message);
            const gigaProductPriceResult = await getProductPrice(message.data.gigaProductId);
            // console.log(gigaProductPriceResult);
            return {
              code: 0,
              data: gigaProductPriceResult,
            };
          } catch (error) {
            return {
              code: 1,
              errorMessage: (error as Error).message,
            };
          }
        }

        // 用来自动生成产品的标题
        if (message.type === MessageType.generatorProductTitle) {
          try {
            const generatorResult = await generateProductTitle(message.data.getProductTitleOptions);
            if (generatorResult.status === 0) {
              return {
                code: 0,
                msg: '生成产品标题成功',
                data: generatorResult.data,
              };
            } else {
              return {
                code: 2,
                msg: `生成产品标题失败: 失败原因 ${generatorResult.status}: ${generatorResult.error} `,
              };
            }
          } catch (error) {
            return {
              code: 1,
              msg: `生成产品标题失败: 需要先登录 postme 网站`,
            };
          }
        }

        // 用来获取 giga 中 api 的 access_token
        if (message.type === MessageType.getGigaAccessToken) {
          try {
            const accessToken = await getAccessToken(
              message.data.clientId,
              message.data.clientSecret,
            );
            return {
              code: 0,
              msg: '获取 access token 成功',
              data: accessToken,
            };
          } catch (error) {
            return {
              code: 1,
              msg: `获取 access token 失败: ${(error as Error).message}`,
            };
          }
        }

        // 获取 giga 的资源包
        if (message.type === MessageType.getGigaResource) {
          return getGigaResource(message.data.gigaProductId);
        }

        // 设置代理
        if (message.type === MessageType.setProxy) {
          // console.log(message.data);
          return browser.proxy.settings.set(message.data);
        }

        // 获取代理
        if (message.type === MessageType.getProxy) {
          const proxy = await browser.proxy.settings.get({});
          return {
            code: 0,
            msg: '获取代理成功',
            data: proxy.value,
          };
        }

        if (message.type === MessageType.getTemuUserInfo) {
          try {
            const useInfoResult = await getTemuUserInfo();
            return {
              code: 0,
              data: useInfoResult,
            };
          } catch (error) {
            return {
              code: 1,
              errorMessage: (error as Error).message,
            };
          }
        }

        if (message.type === MessageType.getTemuPageQuery) {
          try {
            const pageQueryResult = await pageQuery(
              {
                ...message.data.options,
              },
              message.data.mallId,
            );
            return {
              code: 0,
              data: pageQueryResult,
            };
          } catch (error) {
            return {
              code: 1,
              errorMessage: (error as Error).message,
            };
          }
        }

        if (message.type === MessageType.solveGigaCaptcha) {
          try {
            const { status } = await solveGigaCaptcha(message.data.gigaProductId);
            if (status === 'success') {
              return {
                code: 0,
              };
            } else {
              return {
                code: 2,
                errorMessage: '破解验证码失败',
              };
            }
          } catch (error) {
            return {
              code: 1,
              errorMessage: (error as Error).message,
            };
          }
        }

        // 处理需要跨域的请求
        if (message.type === MessageType.corssRequest) {
          try {
            const data = message.data;

            // 用于获取图像生成的位置
            if (data.kind === 'comfyUiGetImageGenerationLocation') {
              const config = data.config;
              const { url } = config;
              const result =
                await getImageGenerationLocation<GetImageGenerationLocationResult>(url);
              return {
                code: 0,
                data: result,
              };
            }
            // 上传图像
            if (data.kind === 'comfyUiUploadImage') {
              const config = data.config;
              const { url, dataUrl, name } = config;
              // console.log(url, dataUrl);
              const blob = await (await fetch(dataUrl)).blob();
              const result = await upLoadImage(url, new File([blob], name));
              return {
                code: 0,
                data: result,
              };
            }

            // 创建图像
            if (data.kind === 'comfyUiCreateImage') {
              const config = data.config;
              const { url, prompt } = config;
              // console.log(url, dataUrl);
              const result = await createImage(url, prompt);
              return {
                code: 0,
                data: result,
              };
            }

            // 下载图像
            if (data.kind === 'comfyUiDownloadImage') {
              const config = data.config;
              const { url } = config;
              const result = await downloadImage(url);
              const dataUrl = await getDataUrl(result);
              return {
                code: 0,
                data: dataUrl,
              };
            }
          } catch (error) {
            return {
              code: 1,
              message: (error as Error).message,
            };
          }
        }
      },
    );

    browser.contextMenus.onClicked.addListener(async (info, tab) => {
      if (info.menuItemId === 'giga-resource-info') {
        const tab = await getCurrentTab();
        if (tab && tab.id) {
          browser.tabs.sendMessage(tab.id, {
            type: MessageType.gigaResourceInfo,
          });
        }
      }
    });
  },
});
